package china.lzy.service.impl;

import china.lzy.dao.GoodsMapper;
import china.lzy.entity.ResCode;
import china.lzy.entity.ResResult;
import china.lzy.entity.dto.PageDto;
import china.lzy.entity.pojo.Goods;
import china.lzy.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

/**
 * @author lzy
 * @description goods
 * @date 2021-08-16
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public ResResult insert(Goods goods) {

        // valid
        if (goods == null||goods.getShopId()==null) {
            return ResResult.ResResultBuilder("必要参数缺失", ResCode.OPERATE_ERROR);
        }
        try {
            goodsMapper.insert(goods);
            return ResResult.ResResultBuilder(ResCode.SAVE_OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResResult.ResResultBuilder(ResCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ResResult delete(int id) {
        int ret = goodsMapper.delete(id);
        return ret > 0 ? ResResult.ResResultBuilder(ResCode.DELETE_OK) : ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
    }

    @Override
    public ResResult update(Goods goods) {
        int ret = goodsMapper.update(goods);
        return ret > 0 ? ResResult.ResResultBuilder(ResCode.OPERATE_OK) : ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
    }

    @Override
    public ResResult load(int id) {
        Goods goods = goodsMapper.load(id);
        return ResResult.ResResultBuilder(goods, ResCode.OPERATE_OK);
    }

    @Override
    public ResResult pageList(PageDto pageDto) {
        if (pageDto.getPageNum() == 0) {
            pageDto.setPageNum(1);
        }
        if (pageDto.getPageSize() == 0) {
            pageDto.setPageSize(10);
        }
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<Goods> goods = goodsMapper.pageList();
        PageInfo<Goods> pageInfo = new PageInfo<>(goods);
        // result
        pageDto.setRecords(goods);
        pageDto.setTotal((int) pageInfo.getTotal());
        return ResResult.ResResultBuilder(pageDto, ResCode.OPERATE_OK);
    }

}